/*
 * GeneratePersonalNotesDialog.java
 *
 *  created: 2.11.2011
 *  charset: UTF-8
 *  license: MIT (X11) (See LICENSE file for full license)
 */
package cz.mp.k3bg.gui;

import cz.mp.k3bg.Images;
import cz.mp.k3bg.core.BookFiles;
import cz.mp.k3bg.core.PersonalNotesGenerator;
import cz.mp.k3bg.log.LoggerManager;
import cz.mp.util.GuiUtils;
import cz.mp.util.StringUtils;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import static cz.mp.k3bg.Images.*;
import static cz.mp.k3bg.TextSource.*;

/**
 * Dialog pro generování osobních poznámek jako je věnování, báseň, citát.
 * 
 * @author Martin Pokorný
 * @version 0.1
 * @see PersonalNotesGenerator
 */
public class GeneratePersonalNotesDialog extends GenerateDialog {

    private static final boolean DEBUG = false;
    private static final Logger logger =
            LoggerManager.getLogger(GeneratePersonalNotesDialog.class, DEBUG);

    private static GeneratePersonalNotesDialog instance = null;

    private JLabel fileNameLabel = new JLabel(getLocText("gui.bookfiles.generate.file_name"));
    private JTextField fileNameField = new JTextField();

    private JPanel notesPanel = new JPanel();
    
    private static final int MAX_NOTES = 6;
    private NotePanel[] notes = new NotePanel[MAX_NOTES];    
    private static final int DEFAULT_VISIBLE_NOTES = 1;
    private int visibleNotes = DEFAULT_VISIBLE_NOTES;
    
    private JButton plusNoteButton = new JButton(Images.getImage(PLUS));
    
    private JButton generateButton = new JButton(
            getLocText("gui.bookfiles.generate.generate"), Images.getImage(OK));
    private JButton cancelButton = new JButton(
            getLocText("gui.cancel"), Images.getImage(CANCEL));
    
    private PersonalNotesGenerator pnGen;

    // -----

    /** */
    public GeneratePersonalNotesDialog() {
        super(MainFrame.getInstance());
        initComponents();
        initLayout();
        initEventHandlers();
        initDialog();
    }

    /**
     *
     * @return
     */
    private static GeneratePersonalNotesDialog getInstance() {
        if (instance == null) {
            instance = new GeneratePersonalNotesDialog();
        }
        return instance;
    }

    /**
     *
     */
    public static String showDialog(BookFiles bookFiles)  {
        getInstance();

        return instance.showThisDialog(bookFiles);
    }

    /**
     *
     * @param bookFiles
     */
    private String showThisDialog(BookFiles bookFiles) {
        clearAll();
        visibleNotes = DEFAULT_VISIBLE_NOTES;
        plusNoteButton.setVisible(true);
        updateNotesVisible();

        generatedFileName = null;
        this.bookFiles = bookFiles;

        if (bookFiles != null) {
            pnGen = new PersonalNotesGenerator(bookFiles);
            
            setVisible(true);
        }

        return generatedFileName;
    }

    /**
     * 
     */
    private void initDialog() {
        setTitle(getLocText("gui.bookfiles.generate.pn.title"));

        pack();
        setMinimumSize(new Dimension(400, 450));
        setSize(MainFrame.getInstance().getWidth() - 60, MainFrame.getInstance().getHeight() - 40);
            
        setLocationRelativeTo(MainFrame.getInstance());

        GuiUtils.addHideActionWithEscapeKey(this);
    }

    /**
     *
     */
    private void initComponents() {
        fileNameLabel.setLabelFor(fileNameField);

        fileNameField.setEditable(false);
        fileNameField.setText(BookFiles.DEFAULT_PERSONALNOTES_FILENAME);
        
        plusNoteButton.setToolTipText(getLocText("gui.bookfiles.generate.pn_plus.tooltip"));
                
        for (int i = 0; i < notes.length; i++) {
            notes[i] = new NotePanel();            
        }
                
        notesPanel.setLayout(new MigLayout("wrap",
                "0[]para[]0",
//                "0[]0",
                "0[]para"));
        for (NotePanel notePanel : notes) {
//        for (int i = 0; i < notes.length; i++) {
//            notesPanel.add(notes[i], "hidemode 3");
            notesPanel.add(notePanel, "hidemode 3");
        }
        notesPanel.add(plusNoteButton, "hidemode 3, top");

        getRootPane().setDefaultButton(generateButton);
        
        updateNotesVisible();
    }

    /**
     *
     */
    private void initLayout() {
        this.setLayout(new MigLayout("",
                "unrel[label]rel[fill,grow]unrel",
//                "unrel[]para[fill,grow]para[]para[bottom,nogrid]unrel"));
                "unrel[]para[fill,grow]para[bottom,nogrid]unrel"));

        this.add(fileNameLabel);
        this.add(fileNameField, "wrap 2*para");

        this.add(notesPanel, "spanx 2, wrap");
        
        this.add(generateButton, "tag ok, sg b");
        this.add(cancelButton, "tag cancel, sg b");
    }

    /**
     *
     */
    private void initEventHandlers() {
        plusNoteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {                
                if(visibleNotes >= MAX_NOTES-1) {
                    plusNoteButton.setVisible(false);
                }
                visibleNotes++;
                updateNotesVisible();
            }
        });
                
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                generate();

                if (generatedFileName != null) {
                    setVisible(false);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                setVisible(false);
            }
        });
    }    

    /**
     * 
     */
    private void updateNotesVisible() {
        for (int i=notes.length-1; i>0; i--) {
            notes[i].setVisible(false);
        }
        for (int i=0; i<visibleNotes; i++) {
            notes[i].setVisible(true);
        }
    }        
            
    /**
     * 
     */
    public void clearAll() {
        for (int i=0; i<notes.length-1; i++) {
            notes[i].clear();
        }        
    }



    @Override
    protected void generate() {
        if (pnGen == null) {
            throw new IllegalStateException("pnGen = null");
        }

        try {
            bookFiles.setDefaultPersonalNotes();

            // podle toho zda je vyplněný autor se určí typ poznámky ...
            for (NotePanel notePanel : notes) {
                if (StringUtils.isBlank(notePanel.getText())) {
                    continue;
                }
                else if (StringUtils.isBlank(notePanel.getAuthor())) {
                    pnGen.addDedication(notePanel.getText());
                }
                else {
                    pnGen.addCitation(notePanel.getText(), notePanel.getAuthor());
                }
            }

            pnGen.generate();

            generatedFileName = bookFiles.getPersonalNotes().getPath();
            // ----

            generateBaseStyle();

        } catch (IOException ex) {
            logger.warning(ex.toString());
            if (DEBUG) {  ex.printStackTrace();  }
            Dialogs.showErrorDialog(ex);
        }
    }
    
    // -------------------------------------------------------------------------

    /**
     * 
     */
    private static class NotePanel extends JPanel {
        
        private JLabel authorLabel = new JLabel(getLocText("gui.bookfiles.generate.pn_citation_author"));
        private JTextField authorField = new JTextField();

        private JLabel textLabel = new JLabel(getLocText("gui.bookfiles.generate.pn_text"));
        private JTextArea textArea = new JTextArea();
        private JScrollPane textScrollArea = new JScrollPane(textArea);
        
        // -----
        
        public NotePanel() {
            super();
            initComponents();
            initLayout();
//            initEventHandlers();
        }
        
        /** */
        private void initComponents() {
            authorField.setToolTipText(getLocText("gui.bookfiles.generate.pn_citation_author.tooltip"));
            
            textArea.setLineWrap(false);
            textArea.setWrapStyleWord(false);
            GuiUtils.setDefaultFont(textArea);
            textArea.setTabSize(4);
                    
            textScrollArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            textScrollArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);            
        }
        
        /** */
        private void initLayout() {
            this.setLayout(new MigLayout("wrap",
                    "0[]rel[fill,grow,100:300:]0",
                    "0[fill,grow,60:150:]rel[]0"));

            this.add(textLabel, "growy 0, top, pad rel 0 0 0");
            this.add(textScrollArea);
            
            this.add(authorLabel);
            this.add(authorField);
        }
        
        public void clear() {
            authorField.setText("");
            textArea.setText("");
        }
        
        public String getText() {
            return textArea.getText();
        }

        public String getAuthor() {
            return authorField.getText();
        }
    }   // NotePanel

}   // GeneratePersonalNotesDialog.java
